import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-three-sum',
  templateUrl: './three-sum.component.html',
  styleUrls: ['./three-sum.component.css']
})
export class ThreeSumComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
    const nums = [-1, 0, 1, 2, -1, -4];
    console.log(this.threeSum(nums));
  }

  threeSum(nums: Array<number>) {

    var result = [];
    if (nums.length < 3 || nums === null) return [];
    nums.sort((a, b) => a - b);
    for (var i = 0; i < nums.length; i++) {
      if (i > 0 && nums[i] === nums[i - 1]) continue;
      var target = 0 - nums[i]; // 设置一个目标 此目标和nums[i]+起来应该等于0
      var j = i + 1;
      var k = nums.length - 1;
      while (j < k) {
        if (nums[j] + nums[k] === target) {
          result.push([nums[i], nums[j], nums[k]]);
          while (j < k && nums[j] === nums[j + 1]) j++;
          while (j < k && nums[k] === nums[k - 1]) k--;
          j++;
          k--;
        }
        else if (nums[j] + nums[k] < target) {
          j++;
        }
        else {
          k--;
        }
      }
    }
    return result;
// 复制以上
  }

  // threeSum 结束
}



